package com.xbwang.task;

import com.xbwang.contant.CommonContant;
import com.xbwang.pojo.WxToken;
import com.xbwang.service.WeChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 定时任务
 */
@Component
//@EnableScheduling
public class RefreshTokenTask {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${appId}")
    private String appId;
    @Value("${appsecret}")
    private String appsecret;

    @Resource
    private WeChatService weChatService;
    @Resource
    private RestTemplate restTemplate;

//@Scheduled(cron = "0 0 1 * * ?")每天凌晨1点整

//@Scheduled(cron = "0 30 0 * * ?")每天凌晨0点30分

//@Scheduled(cron = "0 */60 * * * ?")1小时处理一次

    /**
     * 每60分钟执行一次，刷新微信token
     */
    @Scheduled(cron = "0 */60 * * * ?")
    public void task() {
        //1、获取token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appsecret;
        WxToken wxToken = restTemplate.getForObject(url, WxToken.class);
        if (wxToken != null) {
            if (wxToken.getErrcode() != null) {
                logger.error("获取token失败，errorcode:{}",wxToken.getErrcode());
                logger.error("errmsg:{}",wxToken.getErrmsg());
                return ;
            }
        }
        wxToken.setId(CommonContant.ACCESS_TOKEN_ID);
        wxToken.setUpdatetime(new Date());
        //2、更新数据库
        Integer ret = weChatService.updateToken(wxToken);
        if (ret > 0){
            logger.debug("token更新成功！");
            return ;
        }
        logger.error("微信token更新失败！");
        return ;
    }

//    @Scheduled(cron = "0 */1 * * * ?")
//    public void task2(){
//        System.out.println("定时任务....");
//    }
}